package com.dream.myqiyi.account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.py.app.NiActivity;

import com.cloud.httputil.HttpUtil;
import com.dream.myqiyi.R;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class ZiyuanmingxiActivity extends Activity {
	
    private static final String TAG="GudingzichanActivity";
    private static final int NETWORKWRONG=0x20000;
    private static final int GETDATASUC=0x3001;
    private static final int SHOWINFO=0x3002;
    private int pageCount=0;
    private int current_page=1;
    private ArrayList<ZiyuanmingxiObject> showlist=new ArrayList<ZiyuanmingxiObject>();
    private HashMap<String ,String> methods;
    private ListView gdlistView;
    private TextView countpage;
    private Spinner jumppage;
    private JSONObject jsonObject;
    private ZiyuanmingxiAdapter adapter;
    private ArrayAdapter<Integer> pageAdapter ;
    private ProgressBar progressBar;
    private List<Integer> pagearray=new ArrayList<Integer>();
    Dialog jsonDialog = null;
	TextView jsonTextView = null, jsonTitle = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.caiwu_view);
		
		TextView textView1 = (TextView) findViewById(R.id.numtext3);
		TextView textView2 = (TextView) findViewById(R.id.nametext3);
		TextView textView3 = (TextView) findViewById(R.id.unitnotext3);
		textView1.setText(R.string.code);
		textView2.setText(R.string.name);
		textView3.setText(R.string.unitname);
		
	    gdlistView = (ListView) findViewById(R.id.listview_cw);
        jumppage=(Spinner)findViewById(R.id.jumppage);
        Button nextbutton=(Button)findViewById(R.id.nextpagebutton);
        nextbutton.setOnClickListener(listener);
        Button lastbutton=(Button)findViewById(R.id.lastpagebutton);
        lastbutton.setOnClickListener(listener);
        countpage=(TextView)findViewById(R.id.showcountpage);
        progressBar=(ProgressBar)findViewById(R.id.progressBar_caiwu);
        pagearray.add(1);
        System.out.println("==========gudingzichan============");
        
        pageAdapter = new ArrayAdapter<Integer>(this,
                 android.R.layout.simple_spinner_item, pagearray);
        pageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    	 jumppage.setAdapter(pageAdapter);
    	 jumppage.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				TextView textView=(TextView)arg1;
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(20);
                textView.setGravity(Gravity.CENTER);
                textView.setText(arg2+"");
                if(!pagearray.isEmpty()){
                	current_page=pagearray.get(arg2);
                	textView.setText(current_page+"");
                	methods.put("pageIndex", current_page+"");
                	progressBar.setVisibility(View.VISIBLE);
                	new Thread(new DataThread()).start();
                }
				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
    		
		});
		

        methods = new HashMap<String, String>();
        methods.put("sessionid", NiActivity.SESSIONID);
        methods.put("unitno", NiActivity.UNITNO);
        methods.put("planyear", "2013");

        
        adapter=new ZiyuanmingxiAdapter(this,showlist);
		gdlistView.setAdapter(adapter);
        gdlistView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            	 Log.i(TAG, "onItemclick"+i);
                 showJsonDialog(showlist.get(i));
            }
        });
	}
	
   /**
    * show dialog
    * */
	private void showJsonDialog(ZiyuanmingxiObject Object) {
		if (jsonDialog == null) {
			jsonDialog = new Dialog(this,R.style.bktransparentDialog);
			jsonDialog.setCancelable(true);
			jsonDialog.setCanceledOnTouchOutside(false);
			View v = View.inflate(this, R.layout.mydialog, null);
			jsonDialog.setContentView(v);
			jsonTextView = (TextView) v.findViewById(R.id.message);
			jsonTitle = (TextView) v.findViewById(R.id.title);
			v.findViewById(R.id.positiveButton).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (jsonDialog != null) {
								jsonDialog.dismiss();
							}
						}
					});
		}
        jsonTitle.setText(R.string.ziyuanmingxi);
        String content=getString(R.string.code)+"："+Object.getCode()+"\n"
                      +getString(R.string.name)+"："+Object.getName()+"\n"
                      +getString(R.string.unitname)+"："+Object.getUnitname()+"\n"
                      +getString(R.string.resourcetype)+Object.getResourcetype()+"\n"
                      +getString(R.string.unit)+Object.getUnit()+"\n"
                      +getString(R.string.amount)+Object.getAmount()+"\n"
                      +getString(R.string.status)+Object.getStatus()+"\n"
                      +getString(R.string.eastend)+Object.getEastend()+"\n"
                      +getString(R.string.northend)+Object.getNorthend()+"\n"
                      +getString(R.string.southend)+Object.getSouthend()+"\n"
                      +getString(R.string.westend)+Object.getWestend()+"\n"
                      +getString(R.string.entrypeople)+Object.getEntrypeople()+"\n"
                      +getString(R.string.certificateno)+Object.getCertificateno();
		jsonTextView.setText(content);
		jsonDialog.show();
	}

	
	/**
	 * DataThread is use to get data form service 
	 * */
	class DataThread implements Runnable{

		@Override
		public void run() {
			 try{
			    jsonObject=HttpUtil.ziyuanmngxi(methods);
			     if(jsonObject!=null){
			           handler.sendEmptyMessage(SHOWINFO);
			       }else{
			            handler.sendEmptyMessage(NETWORKWRONG);
			        }
			    }catch (Exception e){
			         Log.i(TAG,e.toString());
			         handler.sendEmptyMessage(NETWORKWRONG);
			    }
			
		}
		
	}
	
	/**
	 * get data from xml file method
	 * **/
    public  void getdata(){   	   	
    	showlist.clear();
        try {
            JSONArray itemArray = jsonObject.getJSONArray("items");
            ZiyuanmingxiObject object;
            for (int i = 0; i < itemArray.length(); i++) {
                JSONObject assets = new JSONObject(itemArray.opt(i).toString());
                
                object=new ZiyuanmingxiObject();
                object.setCode(assets.getString("code"));
				object.setName(assets.getString("name"));
				object.setUnitname(assets.getString("unitname"));
				object.setResourcetype(assets.getString("resourcetype"));
				object.setUnit(assets.getString("unit"));
				object.setAmount(assets.getString("amount"));
				object.setStatus(assets.getString("status"));
				object.setEastend(assets.getString("eastend"));
				object.setNorthend(assets.getString("northend"));
				object.setSouthend(assets.getString("southend"));
				object.setWestend(assets.getString("westend"));
				object.setEntrypeople(assets.getString("entrypeople"));
				object.setCertificateno(assets.getString("certificateno"));
                showlist.add(object);
            }
        } catch (JSONException e) {
		  Log.i(TAG, e.toString());
            e.printStackTrace();
        }
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
        	progressBar.setVisibility(View.GONE);
            switch (msg.what){
	            case SHOWINFO:
	            	try {
	            		if(pageCount==0){
	            			String pagecountstring=jsonObject.getString("pageCount");
	            			pageCount=Integer.parseInt(pagecountstring);
	            			countpage.setText(String.format(getString(R.string.countpage),pagecountstring));//展示总页数
	            		    pagearray.clear();
	            		    for(int i=1;i<=pageCount;i++){
	            		    	pagearray.add(i);
	            		    }
	            		    pageAdapter.notifyDataSetChanged();
	            		}
	            		getdata();
						adapter.notifyDataSetChanged();
					} catch (Exception e) {
						e.printStackTrace();
					}
	            	break;
                case NETWORKWRONG:
                    Toast.makeText(ZiyuanmingxiActivity.this, R.string.networkwrong, Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    
    
    /**
     * button function
     * ***/
    OnClickListener listener=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.lastpagebutton:
				if(current_page>1){
					current_page--;
					 methods.put("pageIndex", current_page+"");
					 jumppage.setSelection(current_page-1);//spinner是从0开始的
				//	 progressBar.setVisibility(View.VISIBLE);
				//	 new Thread(new DataThread()).start();
				}
				break;
			case R.id.nextpagebutton:
			   if(current_page<pageCount){
				   current_page++;
				   methods.put("pageIndex", current_page+"");
				   jumppage.setSelection(current_page-1);
				//   progressBar.setVisibility(View.VISIBLE);
				//   new Thread(new DataThread()).start();
			   }
				break;

			default:
				break;
			}
			
		}
	};

}
